package com.glela.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.live.model.v20161101.*;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.glela.api.im.util.IMConfig;
import com.glela.cache.redis.RedisKeys;
import com.glela.common.constant.CommonConstants;
import com.glela.common.util.DateUtil;
import com.glela.common.util.DateUtils;
import com.glela.common.util.JsonUtil;
import com.glela.goods.model.vo.goods.LiveSaleResponse;
import com.glela.live.model.LivePlan;
import com.glela.live.models.ChatRoomInfo;
import com.glela.live.models.CodeSuccessResult;
import com.glela.live.service.ChatRoomService;
import com.glela.live.service.LivePlanService;
import com.glela.live.service.LiveSaleGoodsService;
import com.glela.live.util.LiveConfig;
import com.glela.live.util.RongCloud;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.User;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.Response;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
* @ClassName: ActivitiesController 
* @Description: 小铺来了商品明细活动类控制器
* @author NingChongQing
* @date 2017年10月16日 上午11:37:22
 */
@RestController
@RequestMapping(value = "/live")
public class LiveRoomController extends LiveBaseController{
	private static Logger logger = LoggerFactory.getLogger(LiveRoomController.class);

	@Autowired
    private LivePlanService livePlanService;

	@Autowired
    private ChatRoomService chatRoomService;

	@Autowired
	private LiveSaleGoodsService liveSaleGoodsService;

	@Autowired
	private UserService userService;


	/**
	 * 获取历史推流记录
	 * @param json
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getPushListHistory", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getPushListHistory(@RequestBody JSONObject json) throws Exception {
		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", LiveConfig.accessKey,
					LiveConfig.accessKeySecret);
			DefaultAcsClient client = new DefaultAcsClient(profile);
			String startTime = json.getString("startTime");
			String endTime = json.getString("endTime");
			DescribeLiveStreamsPublishListRequest query = new DescribeLiveStreamsPublishListRequest();
			query.setActionName("DescribeLiveStreamsPublishList");
			query.setDomainName(LiveConfig.vhost);
			query.setAppName(LiveConfig.appName);
			query.setStreamName(json.getString("id"));
			query.setStartTime(DateUtils.getUTCByStr(startTime));
			query.setEndTime(DateUtils.getUTCByStr(endTime));/// *DateUtils.dateFormat(DateUtils.addDay(new
																/// Date(),
																/// -20),
																/// BaseConstants.DATE_FORMAT_UTC)*/);
			DescribeLiveStreamsPublishListResponse result = client.getAcsResponse(query);
			return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("获取历史推流记录失败: {}", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	@RequestMapping("/test")
	public String test() {
		System.out.println("=================================");
		return "ok";
	}

	@RequestMapping(value = "/getm3u8",method = RequestMethod.POST,consumes = "application/json")
	public ResponseEntity<?> getm3u8(@RequestBody JSONObject json){
		String livePlanId = json.getString("id");
		Long currentTime = (System.currentTimeMillis() / 1000) + CommonConstants.LIVE_KEY_VALID_TIME;
		String pullkeyString = "/" + LiveConfig.appName + "/" + livePlanId + ".m3u8-" + currentTime + "-0-0-"
				+ LiveConfig.validKey;
		String md5StrPull = DigestUtils.md5Hex(pullkeyString);
		String pullUrl = "http://" + LiveConfig.vhost + "/" + LiveConfig.appName + "/" + livePlanId + ".m3u8?auth_key="
				+ currentTime + "-0-0-" + md5StrPull;
		JSONObject result = new JSONObject();
		result.put("pullUrl", pullUrl);
		return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
	}

	/**
	 * 查询直播推流地址
	 * @param json
	 * @return
	 */
	@RequestMapping(value = "/getPushUrl", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getPushUrl(@RequestBody JSONObject json, HttpServletRequest request) {
		String livePlanId = json.getString("id");
		/*
		 * if (ParameterUtils.validParams(uid,request.getHeader("userId"))) {
		 * return JsonUtil.getFailJsonStr("缺少必传参数"); } if
		 * (!uid.equals(request.getHeader("userId"))){ return
		 * JsonUtil.getFailJsonStr("非主播不能获取推流信息"); }
		 */
		ChatRoomInfo[] chatroomCreateChatRoomInfo = { new ChatRoomInfo(livePlanId, "") };
		try {
			CodeSuccessResult chatroomCreateResult = RongCloud.getInstance(IMConfig.appKey, IMConfig.appSecret).chatroom
					.create(chatroomCreateChatRoomInfo);
			// RongCloud.getInstance(IMConfig.appKey,
			// IMConfig.appSecret).chatroom.keepLive(uid);
		} catch (Exception e) {
			logger.error("聊天室初始化失败，请重试", e);
			//return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
		String info = getUrlInfo(livePlanId, 0);
		JSONObject jsonInfo = JSONObject.parseObject(info);
		JSONObject result = new JSONObject();
		result.put("pushUrl",jsonInfo.getJSONObject("data").getString("pushUrl"));
		return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
	}

	/**
	 * 查询直播拉流地址
	 *
	 * @param json
	 * @return
	 */
	@RequestMapping(value = "/getPullUrl", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getPullUrl(@RequestBody JSONObject json) {

		try {
			String livePlanId = json.getString("id");
			/*
			 * if
			 * (!("1").equals(redisUtil.get(RedisKey.REDIS_KEY_LIVE_STATUS+uid))
			 * ){ return JsonUtil.getFailJsonStr("直播间处于非直播状态"); }
			 */

			String info = getUrlInfo(livePlanId, 1);
			JSONObject jsonInfo = JSONObject.parseObject(info);
			JSONObject result = new JSONObject();
			result.put("pullUrl",jsonInfo.getJSONObject("data").getString("pullUrl"));
			return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查询直播拉流地址失败: {}", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);

		}

	}

	private String getUrlInfo(String livePlanId, int type) {
		String result = getLiveRoomInfo(livePlanId,"");
		if (!JSONObject.parseObject(result).getBoolean("success")) {
			return result;
		}
		if (0 == type) {
			String pushUrl = JSONObject.parseObject(result).getJSONObject("data").getString("pushUrl");
			JSONObject jsonResult = new JSONObject();
			jsonResult.put("pushUrl", pushUrl);
			return JsonUtil.getSuccessJsonStr("ok", jsonResult);
		} else {
			String pullUrl = JSONObject.parseObject(result).getJSONObject("data").getString("pullUrl");
			JSONObject jsonResult = new JSONObject();
			jsonResult.put("pullUrl", pullUrl);
			return JsonUtil.getSuccessJsonStr("ok", jsonResult);
		}
	}


	/**
	 *
	 * @param uid
	 * @param type 0推流 1拉流
	 * @return
	 */
	private String getLiveRoomInfo(String livePlanId,String clientType) {
		/*
		 * String redisResult =
		 * redisUtil.get(RedisKey.REIDS_KEY_LIVEROOM_PULL_PUSH_ADDRESS+uid);
		 * if(StringUtils.isNotBlank(redisResult)){ return
		 * JsonUtil.getSuccessJsonStr("ok",redisResult); }
		 */
		/*
		 * LiveRoom liveRoom =
		 * liveRoomService.getLiveRoomByUid(Long.valueOf(uid)); if
		 * (liveRoom==null){ return JsonUtil.getFailJsonStr("未查询到对应的直播间信息"); }
		 */
		Long currentTime = (System.currentTimeMillis() / 1000) + CommonConstants.LIVE_KEY_VALID_TIME;
		String keyString = "/" + LiveConfig.appName + "/" + livePlanId + "-" + currentTime + "-0-0-"
				+ LiveConfig.validKey;
		String md5Str = DigestUtils.md5Hex(keyString);
		String pushUrl = LiveConfig.pushUrl + LiveConfig.appName + "/" + livePlanId + "?vhost=" + LiveConfig.vhost
				+ "&auth_key=" + currentTime + "-0-0-" + md5Str;
		/*String pullUrl = "rtmp://" + LiveConfig.vhost + "/" + LiveConfig.appName + "/" + livePlanId + "?auth_key="
				+ currentTime + "-0-0-" + md5Str;*/
		/*String m3u8keyString = "/" + LiveConfig.appName + "/" + livePlanId + ".m3u8-" + currentTime + "-0-0-"
				+ LiveConfig.validKey;
		String m3u8md5Str = DigestUtils.md5Hex(m3u8keyString);
		String pullUrl = "http://" + LiveConfig.vhost + "/" + LiveConfig.appName + "/" + livePlanId + ".m3u8?auth_key="
				+ currentTime + "-0-0-" + m3u8md5Str;*/
		/*Long currentTime = (System.currentTimeMillis() / 1000) + CommonConstants.LIVE_KEY_VALID_TIME;*/
		JSONObject result = new JSONObject();
		if (StringUtils.isBlank(clientType)){
			String pullkeyString = "/" + LiveConfig.appName + "/" + livePlanId + ".flv-" + currentTime + "-0-0-"
					+ LiveConfig.validKey;
			String pullmd5Str = DigestUtils.md5Hex(pullkeyString);
			String pullUrl = "http://"+ LiveConfig.vhost + "/" + LiveConfig.appName + "/" + livePlanId + ".flv?auth_key="
					+ currentTime + "-0-0-" + pullmd5Str;
			result.put("pullUrl", pullUrl);
		}else{
			String pullkeyString = "/" + LiveConfig.appName + "/" + livePlanId + ".m3u8-" + currentTime + "-0-0-"
					+ LiveConfig.validKey;
			String pullmd5Str = DigestUtils.md5Hex(pullkeyString);
			String pullUrl = "http://"+ LiveConfig.vhost + "/" + LiveConfig.appName + "/" + livePlanId + ".m3u8?auth_key="
					+ currentTime + "-0-0-" + pullmd5Str;
			result.put("pullUrl", pullUrl);
		}
		result.put("pushUrl", pushUrl);
		// redisUtil.set(RedisKey.REIDS_KEY_LIVEROOM_PULL_PUSH_ADDRESS+uid,result.toJSONString(),600);
		return JsonUtil.getSuccessJsonStr("ok", result.toJSONString());
	}

	/**
	 * 查询直播间在线人数，最外层返回当前应用总的在线人数
	 * @param json
	 * @return
	 * @throws ClientException
	 */
	@RequestMapping(value = "/getStreamOnlineUserNum", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getStreamOnlineUserNum(@RequestBody JSONObject json) throws ClientException {
		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", LiveConfig.accessKey,
					LiveConfig.accessKeySecret);
			DefaultAcsClient client = new DefaultAcsClient(profile);
			String id = json.getString("id");
			DescribeLiveStreamOnlineUserNumRequest describeLiveStreamOnlineUserNumRequest = new DescribeLiveStreamOnlineUserNumRequest();
			describeLiveStreamOnlineUserNumRequest.setActionName("DescribeLiveStreamOnlineUserNum");
			describeLiveStreamOnlineUserNumRequest.setDomainName(LiveConfig.vhost);
			describeLiveStreamOnlineUserNumRequest.setAppName(LiveConfig.appName);
			describeLiveStreamOnlineUserNumRequest.setStreamName(id);
			DescribeLiveStreamOnlineUserNumResponse result = client
					.getAcsResponse(describeLiveStreamOnlineUserNumRequest);
			return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查询直播间在线人数: {}", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);

		}
	}

	/**
	 * 禁止直播流推送
	 * @param json
	 * @return
	 * @throws ClientException
	 */
	@RequestMapping(value = "/forbidLiveStream", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> forbidLiveStream(@RequestBody JSONObject json) throws ClientException {

		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", LiveConfig.accessKey,
					LiveConfig.accessKeySecret);
			DefaultAcsClient client = new DefaultAcsClient(profile);
			String id = json.getString("id");
			ForbidLiveStreamRequest forbidLiveStreamRequest = new ForbidLiveStreamRequest();
			forbidLiveStreamRequest.setActionName("ForbidLiveStream");
			forbidLiveStreamRequest.setDomainName(LiveConfig.vhost);
			forbidLiveStreamRequest.setAppName(LiveConfig.appName);
			forbidLiveStreamRequest.setStreamName(id);
			forbidLiveStreamRequest.setLiveStreamType("publisher");
			String date = DateUtil.addDayToLongString(1);
			forbidLiveStreamRequest.setResumeTime(DateUtils.getUTCByStr(date));
			ForbidLiveStreamResponse result = client.getAcsResponse(forbidLiveStreamRequest);
			return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("禁止直播流推送失败: {}", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 恢复直播流推送
	 * @param json
	 * @return
	 * @throws ClientException
	 */
	@RequestMapping(value = "/resumeLiveStream", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> resumeLiveStream(@RequestBody JSONObject json) throws ClientException {
		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", LiveConfig.accessKey,
					LiveConfig.accessKeySecret);
			DefaultAcsClient client = new DefaultAcsClient(profile);
			String id = json.getString("id");// 直播计划id
			ResumeLiveStreamRequest resumeLiveStreamRequest = new ResumeLiveStreamRequest();
			resumeLiveStreamRequest.setActionName("ResumeLiveStream");
			resumeLiveStreamRequest.setDomainName(LiveConfig.vhost);
			resumeLiveStreamRequest.setAppName(LiveConfig.appName);
			resumeLiveStreamRequest.setStreamName(id);
			resumeLiveStreamRequest.setLiveStreamType("publisher");
			ResumeLiveStreamResponse result = client.getAcsResponse(resumeLiveStreamRequest);
			return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("恢复直播流推送失败: {}", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 设置推流回调地址
	 * @param json
	 * @return
	 * @throws ClientException
	 */
	@RequestMapping(value = "/setPushNotifyUrl", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> setPushNotifyUrl(@RequestBody JSONObject json) throws ClientException {

		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", LiveConfig.accessKey,
					LiveConfig.accessKeySecret);
			DefaultAcsClient client = new DefaultAcsClient(profile);
			String notifyUrl = json.getString("notifyUrl");
			SetLiveStreamsNotifyUrlConfigRequest query = new SetLiveStreamsNotifyUrlConfigRequest();
			query.setActionName("SetLiveStreamsNotifyUrlConfig");
			query.setDomainName(LiveConfig.vhost);
			query.setNotifyUrl(notifyUrl);
			SetLiveStreamsNotifyUrlConfigResponse result = client.getAcsResponse(query);
			return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("设置推流回调地址失败: {}", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 查询直播回调地址
	 * @param json
	 * @return
	 * @throws ClientException
	 */
	@RequestMapping(value = "/getLiveStreamNotifyUrl", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getLiveStreamNotifyUrl() {
		IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", LiveConfig.accessKey,
				LiveConfig.accessKeySecret);
		DefaultAcsClient client = new DefaultAcsClient(profile);
		DescribeLiveStreamsNotifyUrlConfigRequest request = new DescribeLiveStreamsNotifyUrlConfigRequest();
		request.setActionName("DescribeLiveStreamsNotifyUrlConfig");
		request.setDomainName(LiveConfig.vhost);
		try {
			DescribeLiveStreamsNotifyUrlConfigResponse result = client.getAcsResponse(request);
			return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
		} catch (ClientException e) {
			logger.error("查询直播回调地址失败: {}", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);

		}
	}

	/**
	 * 删除直播回调地址
	 * @return
	 * @throws ClientException
	 */
	@RequestMapping(value = "/delLiveNotifyUrl", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> delLiveNotifyUrl() throws ClientException {

		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", LiveConfig.accessKey,
					LiveConfig.accessKeySecret);
			DefaultAcsClient client = new DefaultAcsClient(profile);
			DeleteLiveStreamsNotifyUrlConfigRequest request = new DeleteLiveStreamsNotifyUrlConfigRequest();
			request.setDomainName(LiveConfig.vhost);
			request.setActionName("DeleteLiveStreamsNotifyUrlConfig");
			DeleteLiveStreamsNotifyUrlConfigResponse result = client.getAcsResponse(request);
			return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("删除直播回调地址失败: {}", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);

		}
	}

	/**
	 * 查询直播在线推流列表
	 * @param json
	 * @return
	 * @throws ClientException
	 */
	@RequestMapping(value = "/getLiveOnlineList", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getLiveOnlineList() throws ClientException {

		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", LiveConfig.accessKey,
					LiveConfig.accessKeySecret);
			DefaultAcsClient client = new DefaultAcsClient(profile);
			DescribeLiveStreamsOnlineListRequest request = new DescribeLiveStreamsOnlineListRequest();
			request.setActionName("DescribeLiveStreamsOnlineList");
			request.setDomainName(LiveConfig.vhost);
			request.setAppName(LiveConfig.appName);
			DescribeLiveStreamsOnlineListResponse result = client.getAcsResponse(request);
			return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查询直播在线推流列表失败: {}", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 查询直播推流码率
	 * @param json
	 * @return
	 * @throws ClientException
	 */
	@RequestMapping(value = "/getLiveStreamBitRate", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getLiveStreamBitRate(@RequestBody JSONObject json) throws ClientException {
		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", LiveConfig.accessKey,
					LiveConfig.accessKeySecret);
			DefaultAcsClient client = new DefaultAcsClient(profile);
			String id = json.getString("id");// 直播计划id
			String startTime = json.getString("startTime");
			String endTime = json.getString("endTime");
			DescribeLiveStreamsFrameRateAndBitRateDataRequest request = new DescribeLiveStreamsFrameRateAndBitRateDataRequest();
			request.setActionName("DescribeLiveStreamBitRateData");
			request.setDomainName(LiveConfig.vhost);
			request.setAppName(LiveConfig.appName);
			request.setStreamName(id);
			request.setStartTime(DateUtils.getUTCByStr(startTime));
			request.setEndTime(DateUtils.getUTCByStr(endTime));
			DescribeLiveStreamsFrameRateAndBitRateDataResponse result = client.getAcsResponse(request);
			return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查询直播推流码率失败", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);

		}
	}

	/**
	 * 查询直播黑名单列表
	 * @return
	 * @throws ClientException
	 */
	@RequestMapping(value = "/getBlockList", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getBlockList() throws ClientException {

		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", LiveConfig.accessKey,
					LiveConfig.accessKeySecret);
			DefaultAcsClient client = new DefaultAcsClient(profile);
			DescribeLiveStreamsBlockListRequest request = new DescribeLiveStreamsBlockListRequest();
			request.setDomainName(LiveConfig.vhost);
			request.setActionName("DescribeLiveStreamsBlockList");
			DescribeLiveStreamsBlockListResponse result = client.getAcsResponse(request);
			return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查询直播黑名单列表失败: {}", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

    @RequestMapping(value = "/getPullStreamInfo",method = RequestMethod.POST,consumes = "application/json")
    public ResponseEntity<?> getPullStreamInfo(@RequestBody JSONObject json,HttpServletRequest request){
		try {
			if (StringUtils.isBlank(json.getString("id"))) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			LivePlan livePlan = livePlanService.getById(json.getIntValue("id"));
			if (livePlan == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C90001), HttpStatus.OK);
			}
			if (livePlan.getStatus() == 0 || livePlan.getStatus() == 1) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C90002), HttpStatus.OK);
			}
			if (livePlan.getStatus() == 3) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C90003), HttpStatus.OK);
			}
			String clientType = "";
			if (request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_h5) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_WX)) {
				clientType = "h5";
			}
			if (!"h5".equals(clientType)) {
				User cuser = userService.getUser(json.getLongValue("userId"));
				if (cuser == null) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C90006), HttpStatus.OK);
				}
			}
			User user = userService.getUser(Long.valueOf(livePlan.getLiveuserId()));
			String pullInfo = getLiveRoomInfo(livePlan.getId() + "", clientType);
			String pullUrl = JSONObject.parseObject(pullInfo).getJSONObject("data").getString("pullUrl");
			String token = "";
			if (!"h5".equals(clientType)) {
				JSONObject chatJson = new JSONObject();
				chatJson.put("userId", json.getString("userId"));
				String chatToken = chatRoomService.getToken(chatJson);
				token = JSONObject.parseObject(chatToken).getJSONObject("data").getString("token");
			}else{
				if (StringUtils.isNotBlank(json.getString("userId"))){
					JSONObject chatJson = new JSONObject();
					chatJson.put("userId", json.getString("userId"));
					String chatToken = chatRoomService.getToken(chatJson);
					token = JSONObject.parseObject(chatToken).getJSONObject("data").getString("token");
				}else{
					JSONObject chatJson = new JSONObject();
					long uuid = System.currentTimeMillis()+(int)(Math.random() * 999 + 1);
					chatJson.put("userId", uuid);
					String chatToken = chatRoomService.getToken(chatJson);
					token = JSONObject.parseObject(chatToken).getJSONObject("data").getString("token");
				}

			}
			List<LiveSaleResponse> list = liveSaleGoodsService.getLiveSaleByLivePlanId(livePlan.getId());
			JSONObject result = new JSONObject();
			result.put("pullUrl", pullUrl);
			result.put("token", token);
			result.put("goodsList", list);
			result.put("goodsNum", list.size());
			result.put("chatRoomId", livePlan.getId());
			result.put("liveUserIcon", user == null ? "" : user.getPicture());//头像
			result.put("title", livePlan.getTitle());//直播标题
			int uNum = redisUtil.get(RedisKeys.LIVE_PLAN_USER_NUMBER + livePlan.getId()) == null ? 0 : (Integer.valueOf(redisUtil.get(RedisKeys.LIVE_PLAN_USER_NUMBER + livePlan.getId())) + livePlan.getAddUserNum());
			result.put("userNum", uNum > 0 ? uNum : 0);//观众数
			result.put("zNum", redisUtil.get(RedisKeys.LIVE_PLAN_TOTAL_LIKE_NUM + livePlan.getId()) == null ? 0 : redisUtil.get(RedisKeys.LIVE_PLAN_TOTAL_LIKE_NUM + livePlan.getId()));//点赞总数
			result.put("tips", redisUtil.get(RedisKeys.LIVE_ROOM_TIPS) == null ? CommonConstants.liveRoomDefaultTips : redisUtil.get(RedisKeys.LIVE_ROOM_TIPS));
			return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
		}catch (Exception e){
			logger.error("进入直播间失败: {}",e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
    }

    @RequestMapping(value = "/getFlvPullUrl",method = RequestMethod.POST,consumes = "application/json")
	public ResponseEntity<?> getFlvPullUrl(@RequestBody JSONObject jsonObject){
    	String id = jsonObject.getString("id");
		Long currentTime = (System.currentTimeMillis() / 1000) + CommonConstants.LIVE_KEY_VALID_TIME;
		String keyString = "/" + LiveConfig.appName + "/" + id + ".flv-" + currentTime + "-0-0-"
				+ LiveConfig.validKey;
		String md5Str = DigestUtils.md5Hex(keyString);
		String pullUrl = "http://"+ LiveConfig.vhost + "/" + LiveConfig.appName + "/" + id + ".flv?auth_key="
				+ currentTime + "-0-0-" + md5Str;
		JSONObject result = new JSONObject();
		result.put("pullUrl",pullUrl);
		return new ResponseEntity<>(new ResponseResultModel<>(result), HttpStatus.OK);
	}
}
